package com.tristia.service.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.tristia.entity.Book;
import com.tristia.service.BookService;

@Service("bookService")
public class BookServiceJpa implements BookService {

	private EntityManager entityManager;

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}
	
	@Transactional(readOnly = true)
	public Book getById(long id) {
		// TODO Auto-generated method stub
		return entityManager.find(Book.class, id);
	}
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Book> getAll() {
		Query query = entityManager.createNamedQuery("Book.findAll");
		List<Book> books = null;
		books = query.getResultList();
		return books;
	}

	@Transactional(readOnly=false, propagation=Propagation.REQUIRED)
	public boolean save(Book book) {
		
		entityManager.persist(book);
		entityManager.flush();
		
		return true;
	}
	@Transactional(readOnly=false, propagation=Propagation.REQUIRED)
	public boolean update(Book book) {
		entityManager.merge(book);
		entityManager.flush();
		return true;
	}
	@Transactional(readOnly=false, propagation=Propagation.REQUIRED)
	public boolean delete(Book book) {
		book = entityManager.getReference(Book.class, book.getId());
		if (book == null)
			return false;
		entityManager.remove(book);
		entityManager.flush();
		return true;
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public Book findBook(Book book) {
		Book result = null;
		Query queryFindBook = entityManager.createNamedQuery("Book.findBook");
		queryFindBook.setParameter("title", book.getTitle());
		queryFindBook.setParameter("author", book.getAuthor());
		List<Book> books = queryFindBook.getResultList();
		if(books.size() > 0) {
			result = books.get(0);
		}
		return result;
	}
}
